package cn.oowoo.rabbitmq.dlx;

import cn.oowoo.rabbitmq.config.RabbitConfig;
import cn.oowoo.rabbitmq.config.RabbitExchangeTypeEnum;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Author: Zhangbin
 * @Date: 2021/5/9 14:55
 * @Description:  测试DLX-死信消费者（进入死信队列的消息将会在这里被特殊处理）
 **/
public class DlxConsumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = RabbitConfig.createConnection();
        // 创建消息通道
        Channel channel = connection.createChannel();

        //创建一个topic死信交换机
        channel.exchangeDeclare(RabbitConfig.EXCHANGE_DLX_NAME, RabbitExchangeTypeEnum.TOPIC.getExchangeType(),false,false,null);
        //创建死信队列
        channel.queueDeclare(RabbitConfig.QUEUE_DLX_NAME,false,false,false,null);
        //死信交换机、死信队列、路由key绑定
        channel.queueBind(RabbitConfig.QUEUE_DLX_NAME,RabbitConfig.EXCHANGE_DLX_NAME,RabbitConfig.ROUTING_DLX_KEY);

        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg = new String(body, "UTF-8");
                System.out.println("接收到死信消息 : '" + msg + "'");
            }
        };
        channel.basicConsume(RabbitConfig.QUEUE_DLX_NAME, true, consumer);
    }
}
